import {config} from '../config.js'

class HTTP{
    request(params){
      let _self = this;
        if(!params.method){
          params.method ="GET"
        }
        let header = {
          'cookie': wx.getStorageSync("sessionid"),//读取cookie,
          'content-type': 'application/json'
        };
        wx.showLoading({
            title: '加载中',
        })
        wx.request({
            url:config.api_base_url + params.url,
            method:params.method,
            data:params.data,
            header:header,
            success:function(res){

                let data = res.data;
                let errCode = data.errCode;
                let errMessage = data.errMsg;
                let code = res.statusCode.toString()
                if (code.startsWith('2')){
                    if(errCode=="0000"){
                        wx.hideLoading();
                        params.success && params.success(data.data)
                    } else if (errCode == "0010" || errCode == "0015"){
                        //自动登录 0010 session 过期 0015 未登录|| errCode == "0015"
                      wx.hideLoading();
                      _self._autoLogin(params)
                    } else if (errCode == "0011" || errCode=="0012"){
                      wx.hideLoading();
                      params.success && params.success(data)
                    }else{
                      wx.hideLoading();
                      _self._show_error(errCode, params.url+ errMessage)
                    }
                    
                }
                else{
                  wx.hideLoading();
                  _self._show_error(errCode, errMessage)
                }
               
            },
            fail:function(err){
                wx.hideLoading();
                _self._show_error("","服务器异常,请退出小程序,稍后再试。");
            }
        })

}

uploadImages(images,cbfn){
      let _self = this;

      let sequence = images.map(function (item, index) {
        return new Promise(function (resolve, reject) {
          let header;
          header = {
            'cookie': wx.getStorageSync("sessionid"),
            "Content-Type": "multipart/form-data"
          };
          wx.uploadFile({
            url: "https://wxapi.51imu.com/upload/img",
            filePath: item,
            header: header,
            name: 'file',
            formData:{
              "fileType":"1"
            },
            success: function (res) {
              let data = res.data;
              if(typeof data!="object"){
                data = JSON.parse(data);
              }
              if (data.errCode == "0000") {
                wx.hideLoading();
                resolve(data.data.join(''));
              }
              if (data.errCode == "0010") {
                wx.hideLoading();
                _self._show_error("", "session过期");
              }
            },
            fail: function (error) {
              wx.hideLoading();
              reject(error);
            }
          });
        });
      });
      wx.showLoading({
        title: '正在上传图片',
      });

      Promise.all(sequence).then(function (res) {
        wx.hideLoading();
        if (cbfn != undefined) { cbfn(res)};
      }).catch(function (error) {
        wx.hideLoading();
        _self._show_error("", "error");
      });

}



    _show_error(errCode,errMessage){
        wx.showToast({
            title: errCode + errMessage, 
            icon:'none',
            duration:3000
        }) 
    }

    _autoLogin(params){ 
      let self = this;    
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.request({
              url: config.api_base_url + '/sys/getwxinfo',
              data: {
                code: res.code
              },
              success: function (res) {
                let errCode = res.data.errCode;
                if (errCode == '0000') {
                  let data = res.data.data[0];
                  wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
                  let header = {
                    'cookie': res.header["Set-Cookie"]//读取cookie
                  };
                  let location = wx.getStorageSync('location');
                  let loginData;
                  if(location==""){
                     loginData ={
                      "mobileType":"",
                      "geographicLocation":""
                      }
                  }else{
                    loginData=location;
                  }
                  wx.request({
                        url: config.api_base_url + '/usr/islogin',
                        method:"POST",
                        header: header,
                        data:loginData,
                        success: function (res) {
                          let errCode = res.data.errCode;
                          // if (errCode == '0000') {
                          //   let data = res.data.data[0];
                          //   wx.setStorageSync("usercache", data);
                          //   if (params) {
                          //     self.request(params)
                          //   }
                          // }else{
                          //   wx.redirectTo({
                          //     url: '/pages/wxlogin/wxlogin',
                          //     success: function () {
                          //     }
                          //   })
                          // }
                          if (errCode == '0000') {
                          if (res.data.data!=null){
                            let data = res.data.data[0];
                            wx.setStorageSync("usercache", data);
                          }
                          if (params) {
                            self.request(params)
                          }
                          }else{
                            self._show_error(errCode +"自动登录失败");
                          }
                        }
                      });
                }
              },
              fail: function (error) {
                wx.setStorageSync("autoLoginInfo", "自动登录失败");
              }
            })
          } else {
          }
        }
      });
    }
}

export {HTTP}